import { upperFirst } from 'lodash-es'
import { NAME_WHITE_LIST, PATH_WHITE_LIST } from './router.constant'
import type { RouteMeta, RouteRecordRaw, RouteLocationNormalized } from 'vue-router'

/** 首先把你需要动态路由的组件地址全部获取 [vue2 中可以直接用拼接的方式，但是 vue3 中必须用这种方式] */
export const views = import.meta.glob('@/views/**/*.vue', { eager: false }) // 显式声明懒加载（默认）

/** 判断路由是否在白名单 */
export function isWhiteList(to: RouteLocationNormalized): boolean {
  // path 和 name 任意一个匹配上即可
  return PATH_WHITE_LIST.includes(to.path) || NAME_WHITE_LIST.includes(to.name as string)
}

/** 遍历后台传来的路由字符串，转换为组件对象 */
export function generateRoutes(menus: MenuType.Entity[], parentId: string = '0'): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  for (const item of menus) {
    if (item.parentId !== parentId) continue
    const route = {} as RouteRecordRaw
    route.path = item.path
    route.name = upperFirst(item.path.replaceAll('/', ''))
    route.component = buildRouteComponent(item.component, route.name)
    route.meta = buildRouteMeta(item)
    const children = generateRoutes(menus, item.id)
    if (children.length > 0) route.children = children
    routes.push(route)
  }
  return routes
}

/** 根据菜单数据生成对应的路由元信息 */
export function buildRouteMeta(record: MenuType.Entity): RouteMeta {
  const routeMeta: RouteMeta = {}
  routeMeta.icon = record.icon
  routeMeta.title = record.title
  routeMeta.alwaysShow = record.type === 'M'
  routeMeta.full = record.full === 1
  routeMeta.hidden = record.visible === 0
  routeMeta.keepAlive = record.isCache === 1
  return routeMeta
}

/** 根据菜单数据生成对应的路由组件 */
function buildRouteComponent(component: string, name: string) {
  if (!component) return null
  return () => views[`/src/views/${component}.vue`]().then((m: any) => ((m.default.name = name), m))
}
